package org.lex.dbq.model.export;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class HtmlExporter extends AbstractExporter {
	private IDataProcessor<Object, String> trans = new DafaultDataProcessor();

	@Override
	public void exportHeader(ResultSet rs, PrintWriter out) throws IOException, SQLException {
		this.writelnOpenTag("html", out);
		this.writelnOpenTag("body", out);
		out.println("<table border=\"1\">");
		this.writeOpenTag("tr", out);
		ResultSetMetaData meta = rs.getMetaData();
		int columnCount = meta.getColumnCount();
		for (int col = 0; col < columnCount; col++) {
			String columnName = meta.getColumnLabel(col + 1);
			this.writeOpenTag("th", out);
			out.write(columnName);
			this.writeCloseTag("th", out);
		}
		this.writelnCloseTag("tr", out);
	}

	@Override
	public void exportRow(Object[] row, PrintWriter out) throws IOException, SQLException {
		this.writeOpenTag("tr", out);
		for (Object o : row) {
			this.writeOpenTag("td", out);
			String s = trans.toFile(o);
			if (s.isEmpty()) {
				s = "&nbsp;";
			}
			out.write(s);
			this.writeCloseTag("td", out);
		}
		this.writelnCloseTag("tr", out);
	}

	@Override
	public void exportFooter(ResultSet rs, PrintWriter out) throws IOException, SQLException {
		this.writelnCloseTag("table", out);
		this.writelnCloseTag("body", out);
		this.writelnCloseTag("html", out);
	}

	private void writeOpenTag(String tag, PrintWriter out) throws IOException {
		out.write('<');
		out.write(tag);
		out.print('>');
	}

	private void writelnOpenTag(String tag, PrintWriter out) throws IOException {
		out.write('<');
		out.write(tag);
		out.println('>');
	}

	private void writeCloseTag(String tag, PrintWriter out) throws IOException {
		out.write("</");
		out.write(tag);
		out.print('>');
	}

	private void writelnCloseTag(String tag, PrintWriter out) throws IOException {
		out.write("</");
		out.write(tag);
		out.println('>');
	}
}
